package com.epam.necklace.logic.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;
import org.apache.log4j.Logger;

import com.epam.necklace.model.stone.Stone;

public class FileActivity {
	private static final Logger log = Logger.getLogger(FileActivity.class);
	private BufferedReader reader;
	private ObjectOutputStream out;
	private ObjectInputStream in;
	private File necklaceFolder = new File("necklaceFolder");

	public void serialize() throws FileNotFoundException, IOException {

		try {
			reader = new BufferedReader(new InputStreamReader(System.in));
			log.info("Enter the filename where will be your necklace save (Press 0 to return)");
			String path = reader.readLine();
			if (!path.isEmpty()) {
				if (path.equals("0")) {
					return;
				} else {
					necklaceFolder.mkdir();
					File necklaceFile = new File(necklaceFolder, path);
					out = new ObjectOutputStream(new FileOutputStream(
							necklaceFile));
					out.writeObject(Necklace.necklace);
					out.close();
					log.info("Successful operation");
				}
			} else {
				serialize();
			}
		} catch (FileNotFoundException e) {
			log.warn("File not found, try again " + e);
			serialize();
		} catch (IOException e) {
			log.warn("Input problems, try again " + e);
			serialize();
		}
	}

	@SuppressWarnings("unchecked")
	public void deserialize() throws ClassNotFoundException,
			FileNotFoundException, IOException {

		try {
			reader = new BufferedReader(new InputStreamReader(System.in));
			log.info("Enter the filename of your necklace (Press 0 to return)");
			String path = reader.readLine();
			if (!path.isEmpty()) {
				if (path.equals("0")) {
					return;
				} else {
					necklaceFolder.mkdir();
					File necklaceFile = new File(necklaceFolder, path);
					in = new ObjectInputStream(
							new FileInputStream(necklaceFile));
					Necklace.necklace = ((List<Stone>) in.readObject());
					in.close();
					log.info("Successful operation");
				}
			} else {
				deserialize();
			}
		} catch (ClassNotFoundException e) {
			log.warn("Problems with class, try again " + e);
			deserialize();
		} catch (FileNotFoundException e) {
			log.warn("File not found, try again " + e);
			deserialize();
		} catch (IOException e) {
			log.warn("Input problems, try again " + e);
			deserialize();
		}
	}
}